<?php

namespace App\Process;

use App\Model\CountFormidsModel;
use App\Utility\RedisClient;
use EasySwoole\Component\Process\AbstractProcess;

class CountForm extends AbstractProcess
{
    private $isRun = false;
    public function run($arg){
        //定时500ms检测有没有任务，有的话就while死循环执行
        $this->addTick(500,function (){
            if(!$this->isRun){
                $this->isRun = true;
                go(function (){
                    while (true){
                        try{
                            $redisClient = new RedisClient();
                            $task = $redisClient->onQueue('form')->read();
                            if($task){
                                //同一小程序同一天同一page同一小时只有唯一统计数据
                                $redisClient->setPrefix($task['applet']);
                                $name = 'data:formid-'.$task['page'].'-'.$task['date'].'-'.$task['hour'];
                                $model = new CountFormidsModel();
                                $hourInfo = $redisClient->get($name);
                                if(empty($hourInfo)){
                                    //生成插入数据并写入缓存(时效1小时)
                                    $hourInfo = [
                                        'total_nums' => 1,
                                        'user_nums' => 0,
                                        'touch_nums' => 0,
                                        'page' => $task['page'],
                                        'created_at' => $task['date'],
                                        'created_hour' => $task['hour'],
                                        'applet' => $task['applet']
                                    ];
                                    $insertId = $model->create($hourInfo);
                                    $hourInfo['id'] = $insertId;
                                    $redisClient->set($name,$hourInfo,60*60);
                                }
                                $task['type'] = 'formids';
                                $task['model_id'] = $hourInfo['id'];
                                $redisClient->onQueue('count')->push($task);
                                unset($model);
                            }
                            unset($task);
                            unset($redisClient);
                        }catch (\Throwable $throwable){
                            throw new \Exception($throwable->getMessage());
                        }
                    }
                    $this->isRun = false;
                });
            }
        });
    }

    public function onShutDown()
    {
        // TODO: Implement onShutDown() method.
    }

    public function onReceive(string $str, ...$args)
    {
        // TODO: Implement onReceive() method.
    }
}
